package com.cango.qutz.web.auth.user.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.cango.framework.base.opt.DictUtils;
import com.cango.qutz.web.auth.authdept.service.IAuthDeptService;
import com.cango.qutz.web.entity.AuthDeptEntity;
import com.cango.qutz.web.entity.UserEntity;
import com.cango.framework.base.AjaxReturnVO;
import com.cango.framework.base.controller.BaseController;
import com.cango.framework.base.pagination.DataTableRequest;
import com.cango.framework.base.pagination.DataTableResponse;
import com.cango.framework.base.pagination.PageInfo;
import com.cango.framework.base.pagination.PaginationResult;
import com.cango.qutz.web.auth.authdept.service.IAuthDeptService;
import com.cango.qutz.web.auth.position.service.IPositionService;
import com.cango.qutz.web.entity.AuthDeptEntity;
import com.cango.qutz.web.entity.PositionEntity;
import com.cango.qutz.web.entity.UserEntity;
import com.cango.qutz.web.util.Token;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cango.qutz.web.util.Token;

import com.cango.qutz.web.auth.position.service.IPositionService;
import com.cango.qutz.web.auth.user.service.IUserService;
import com.cango.qutz.web.entity.PositionEntity;
import com.google.gson.Gson;

/**
 * <p>
 * ClassName: UserController
 * </p>
 * <p>
 * Description: 用户Controller
 * </p>
 * <p>
 * Author: weih
 * </p>
 * <p>
 * Date: 2015-04-01
 * </p>
 */
@Controller
@RequestMapping("/auth/user")
public class UserController extends BaseController {

    /**
     * log
     */
    private final Log log = LogFactory.getLog(UserController.class);

    /**
     * <p>
     * Field userService: 用户Service注入
     * </p>
     */
    @Autowired
    private IUserService userService;

    /**
     * <p>
     * Field positionService: 岗位Service注入
     * </p>
     */
    @Autowired
    private IPositionService positionService;

    /**
     * <p>
     * Field orgService: 部门Service注入
     * </p>
     */
    @Autowired
    private IAuthDeptService authDeptService;


    @Autowired
    DictUtils dictUtils;
    /**
     * 功能描述: <br>
     * 到用户管理页面
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/toUserManage")
    public String toUserManage() {
        return "/user/userManage";
    }

    /**
     * <p>
     * Description: 到用户列表页面
     * </p>
     * 
     * @return 页面
     */
    @RequestMapping("/toUserList")
    public String toOrgList(String orgCode, Model model) {
        // 设置父节点代码
        model.addAttribute("orgCode", orgCode);
        return "/user/userList";
    }

    /**
     * <p>
     * Description: 分页查询用户记录
     * </p>
     * 
     * @param user 用户对象
     * @param response response
     */
    @RequestMapping("/getListData")
    @ResponseBody
    public DataTableResponse<UserEntity> getListData(UserEntity user, HttpServletResponse response,
                                                     DataTableRequest dataTable) {
        PageInfo pageInfo = new PageInfo(dataTable.getCurrentPage(), dataTable.getiDisplayLength());
        PaginationResult<UserEntity> result = userService.queryListByPage(user, pageInfo);
        return new DataTableResponse(dataTable.getsEcho(), result);
    }

    /**
     * <p>
     * Description: 跳转用户新增页面
     * </p>
     * 
     * @return
     */
    @RequestMapping("/toAddUser")
    @Token(save = true)
    public String toAddUser(String orgCode, Model model) {
        //根据机构CODE得到有效部门
        AuthDeptEntity authDeptEntity = new AuthDeptEntity();
        authDeptEntity.setOrgCode(orgCode);
        List<AuthDeptEntity> deptList =
                this.authDeptService.queryList(authDeptEntity);
        model.addAttribute("orgCode", orgCode);
        model.addAttribute("deptList", deptList);
        model.addAttribute("appList",dictUtils.getDictList(90002));
        return "user/userAdd";
    }

    /**
     * 功能描述: <br>
     * 验证用户名唯一
     *
     * @param loginId 机构代码
     * @return 是否唯一
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/validLoginId")
    @ResponseBody
    public boolean validLoginId(String loginId) {
        return this.userService.validLoginId(loginId);
    }

    /**
     * <p>
     * Description: 保存用户记录
     * </p>
     * 
     * @param user 用户对象
     * @param response
     */
    @RequestMapping("/saveUser")
    @Token(remove = true)
    public void saveUser(UserEntity user, HttpServletResponse response) {
        user.setCreateUser(getSessionUser().getUserId());
        user.setCreateTime(new Date());
        userService.insert(user);
        log.info("用户" + getSessionUser().getUserName() + "新增了用户:" + (new Gson()).toJson(user));
 //        this.positionCache.initCache();
        super.ajaxJson(response, AjaxReturnVO.success());
    }

    /**
     * <p>
     * Description: 跳转用户编辑页面
     * </p>
     * 
     * @param userId 用户对象
     * @param model
     * @return
     */
    @RequestMapping("/toEditUser")
    @Token(save = true)
    public String toEditUser(Integer userId, String orgCode, Model model) {
        UserEntity user = this.userService.queryObjectById(userId);
        // 得到用户岗位信息
        if (null != user.getPositionCode() && !"".equals(user.getPositionCode())) {
            PositionEntity position = this.positionService.queryPosByCode(user.getPositionCode());
            user.setPositionName(position.getPositionName());
        }
        //根据机构CODE得到有效部门
        AuthDeptEntity authDeptEntity = new AuthDeptEntity();
        authDeptEntity.setOrgCode(orgCode);
        List<AuthDeptEntity> deptList = this.authDeptService.queryList(authDeptEntity);
        model.addAttribute("user", user);
        model.addAttribute("deptList", deptList);
        model.addAttribute("appList",dictUtils.getDictList(90002));
        return "user/userEdit";
    }

    /**
     * <p>
     * Description: 保存用户修改记录
     * </p>
     * 
     * @param user 用户对象
     * @param response
     */
    @RequestMapping("/editUser")
    @Token(remove = true)
    public void editUser(UserEntity user, HttpServletResponse response) {
        user.setUpdateUser(getSessionUser().getUserId());
        userService.update(user);
        log.info("用户" + getSessionUser().getUserName() + "修改了用户:" + (new Gson()).toJson(user));
//        this.positionCache.initCache();
        super.ajaxJson(response, AjaxReturnVO.success());
    }

    /**
     * <p>
     * Description: 删除用户记录
     * </p>
     * 
     * @param userId 用户对象
     * @param response
     */
    @RequestMapping("/deleteUser")
    public void deleteUser(Integer userId, HttpServletResponse response) {
        UserEntity user = new UserEntity();
        user.setUserId(userId);
        user.setUpdateUser(getSessionUser().getUserId());
        user.setUpdateTime(new Date());
        userService.delete(user);
        log.info("用户" + getSessionUser().getUserName() + "删除了用户:" + (new Gson()).toJson(user));
        super.ajaxJson(response, AjaxReturnVO.success());
    }

    /**
     * <p>
     * Description: 查看用户明细
     * </p>
     * 
     * @param model
     * @return
     */
    @RequestMapping("/viewUserDetail")
    public String viewUserDetail(Model model) {
        Long userId = this.getSessionUser().getUserId();
        UserEntity user = this.userService.queryObjectById(Integer.parseInt(String.valueOf(userId)));
        // 得到用户岗位信息
        if (null != user.getPositionCode() && !"".equals(user.getPositionCode())) {
            PositionEntity position = this.positionService.queryPosByCode(user.getPositionCode());
            if (null != position && null != position.getPositionName() && !"".equals(position.getPositionName())) {
                user.setPositionName(position.getPositionName());
            }
        }
        model.addAttribute("user", user);
        return "user/userDetailEdit";
    }

    /**
     * <p>
     * Description: 用户修改个人信息记录
     * </p>
     * 
     * @param user 用户对象
     * @param response
     */
    @RequestMapping("/editPersonalInfo")
    public void editPersonalInfo(UserEntity user, HttpServletResponse response) {
        user.setUpdateUser(getSessionUser().getUserId());
        userService.editPersonalInfo(user);
        log.info("用户" + getSessionUser().getUserName() + "修改了用户:" + (new Gson()).toJson(user));
        super.ajaxJson(response, AjaxReturnVO.success());
    }
}
